package com.itheima.config;

import com.itheima.auth.AuthenticationFailureHandler;
import com.itheima.auth.AuthenticationSuccessHandler;
import com.itheima.auth.SpringSecurityUserService;
import com.itheima.auth.ValidateCodeFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SpringSecurityUserService userService;

    @Value("${security.type}")
    private String type;

    @Bean
    public AuthenticationSuccessHandler getAuthenticationSuccessHandler(){
        AuthenticationSuccessHandler handler = new AuthenticationSuccessHandler();
        handler.setType(type);
        return handler;
    }

    @Bean
    public AuthenticationFailureHandler getAuthenticationFailureHandler(){
        AuthenticationFailureHandler handler = new AuthenticationFailureHandler();
        handler.setType(type);
        return handler;
    }

    @Bean
    public BCryptPasswordEncoder getEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public ValidateCodeFilter getValidateCodeFilter(){
        return new ValidateCodeFilter();
    }

    public ReloadableResourceBundleMessageSource getReload(){
        ReloadableResourceBundleMessageSource reload = new ReloadableResourceBundleMessageSource();
        reload.setBasename("classpath:messages_zh_CN");
        return reload;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .authorizeRequests()
                // 跨域预检请求
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                // 登录URL
                .antMatchers("/login.do").permitAll()
                .antMatchers("/login.html").permitAll()
                .antMatchers("/css/**").permitAll()
                .antMatchers("/img/**").permitAll()
                .antMatchers("/js/**").permitAll()
                .antMatchers("/plugins/**").permitAll()
                .antMatchers("/code/image").permitAll()
                // 其他所有请求需要身份认证
                .anyRequest().authenticated();
        http.headers().frameOptions().sameOrigin();
        //配置登录处理器
        http.formLogin().loginPage("/login.html")
        .usernameParameter("username").passwordParameter("password")
                .loginProcessingUrl("/login")
                .successHandler(getAuthenticationSuccessHandler())
                .failureHandler(getAuthenticationFailureHandler());
        // 退出登录处理器
        http.logout().logoutUrl("/logout")
                .logoutSuccessUrl("/login.html")
                .invalidateHttpSession(true);

        http.rememberMe().rememberMeParameter("rememberMe")
                .userDetailsService(userService);
        // 开启登录认证流程过滤器
        http.addFilterBefore(getValidateCodeFilter()
                , UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

}
